<template>
  <topCard queryName="商品名" @SearchInput="getSearchInput" @reset="reset" />
  <el-card class="bottomCard" v-loading="loading">
    <el-button @click="addDrawer" type="primary">添加</el-button>
    <el-button
      @click="deleteSelectItem"
      type="danger"
      :disabled="!selectArr.length"
    >
      批量删除
    </el-button>
    <el-table
      class="bottom-table"
      border
      :data="userList"
      @selection-change="selectChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column
        show-overflow-tooltip
        label="用户账号"
        align="center"
        property="username"
      />
      <el-table-column
        show-overflow-tooltip
        label="用户名称"
        align="center"
        property="name"
      />
      <el-table-column align="center" label="头像">
        <template #default="scope">
          <el-avatar
            :size="50"
            :src="'http://localhost:3000' + scope.row.avatar"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别">
        <template #default="scope">
          {{ getGenderLabel(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column label="用户角色" align="center">
        <template #default="scope">
          {{ getRoleLabel(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" align="center">
        <template #default="scope">
          <div class="tags">
            <el-tag @click="editItem(scope.row)">编辑</el-tag>
            <el-tag @click="deleteItem(scope.row._id)" type="danger">
              删除
            </el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <Pagination
      :pagination="pagination"
      :handleCurrentChange="handleCurrentChange"
      :handleSizeChange="handleSizeChange"
    />
  </el-card>
  <!-- 添加与更新 -->
  <el-drawer
    class="drawer"
    v-model="drawer"
    :title="userParams._id ? `修改用户信息` : `添加用户信息`"
    size="26%"
    :before-close="handleClose"
  >
    <template #default>
      <el-form
        label-width="100px"
        size="large"
        :rules="addRules"
        :model="userParams"
        ref="subUserFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="userParams.username" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams._id">
          <el-input
            placeholder="请输入密码"
            show-password
            type="password"
            v-model="userParams.password"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input placeholder="请输入名称" v-model="userParams.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userParams.gender" placeholder="请选择性别">
            <el-option
              v-for="item in gender"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userParams.role" placeholder="请选择性别">
            <el-option
              v-for="item in role"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChange"
          >
            <img v-if="userParams.avatar" :src="uploadAvatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="subUserParams">提交</el-button>
      <el-button @click="drawer = false">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import topCard from '@/components/topCard/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { formatDateTime } from '@/utils/utils'
import { ElMessageBox, ElForm, ElMessage } from 'element-plus'
import { UserParams, GenderArray, RoleArray } from './type'
import {
  addUserInfo,
  reqUserInfoList,
  updateuserinfo,
  deleteuserinfo,
  searchUserinfobyid
} from '@/api/acl/user'
const pagination = reactive({
  pageSize: 3,
  currentPage: 1,
  total: 0,
})
const selectArr = ref<any[]>([])
let loading = ref(false)
//查询用户input
let inputName = ref('')
const getSearchInput = (input: string) => {
  inputName.value = input
  UserInfoList()
}
let drawer = ref<boolean>(false)
type FormInstance = InstanceType<typeof ElForm>
const subUserFormRef = shallowRef<FormInstance>()

const gender: GenderArray = [
  {
    value: 0,
    label: '保密',
  },
  {
    value: 1,
    label: '男',
  },
  {
    value: 2,
    label: '女',
  },
]
const role: RoleArray = [
  {
    value: 0,
    label: '超级管理员',
  },
  {
    value: 1,
    label: '店长',
  },
  {
    value: 2,
    label: '店员',
  },
]
const addRules = reactive<any>({
  username: [
    { required: true, message: '请输入登录用户名', trigger: 'blur' },
    { required: true, min: 5, message: '账号长度最少五位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { required: true, min: 6, message: '密码长度最少六位', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { required: true, min: 1, message: '请输入用户昵称', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  avatar: [{ required: true, message: '请选择头像', trigger: 'change' }],
})
let userParams: UserParams = reactive({
  username: '',
  password: '',
  name: '',
  gender: '',
  avatar: '',
  file: '',
})
let userList = ref<any>([])
//计算是否是展示哪一种图片
const uploadAvatar = computed(() => {
  return userParams.avatar.includes('blob')
    ? userParams.avatar
    : 'http://localhost:3000' + userParams.avatar
})
// 根据 value 值获取 label 的函数
function getGenderLabel(value: any): string {
  // value = value.toString()
  const genderItem = gender.find((item) => item.value === value)
  return genderItem ? genderItem.label : '未知'
}
// 根据 value 值获取 label 的函数
function getRoleLabel(value: any): string {
  // value = value.toString()
  const roleItem = role.find((item) => item.value === value)
  return roleItem ? roleItem.label : '未知'
}

onMounted(async () => {
  UserInfoList()
})

//获取用户信息列表
const UserInfoList = async () => {
  try {
    loading.value = true
    let res = await reqUserInfoList(
      pagination.currentPage,
      pagination.pageSize,
      inputName.value,
    )
    if (res.code == 200) {
      pagination.total = res.total
      userList.value = res.data
      loading.value = false
    }
  } catch (error) {
    console.error(error) // 处理错误
  } finally {
    loading.value = false // 无论成功或失败，都结束加载
  }
}

const addDrawer = () => {
  userParams.username = ''
  userParams.password = ''
  userParams.name = ''
  userParams.gender = ''
  userParams.avatar = ''
  userParams.file = ''
  userParams._id = ""
  userParams.role = ""
  drawer.value = true
}

//编辑
const editItem = async(row: any) => {
  drawer.value = true
  const res = await searchUserinfobyid(row._id)
  Object.assign(userParams, res.data)
  //清除上一次报错的信息
  nextTick(() => {
    for (let key in userParams) {
      subUserFormRef.value?.clearValidate(key)
    }
  })
}

//关闭抽屉
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定退出提交吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

// 选择头像回调
const handleChange = (file: any) => {
  //本地回显
  userParams.avatar = URL.createObjectURL(file.raw)
  //传给后端
  userParams.file = file.raw
}
// 提交用户信息
const subUserParams = async () => {
  try {
    await subUserFormRef.value?.validate()
    const params = new FormData()
    for (let i in userParams) {
      params.append(i, userParams[i])
    }
    try {
      let res
      if (params.get('_id')) {
        res = await updateuserinfo(params)
      } else {
        res = await addUserInfo(params)
      }
      if (res.code == 200) {
        ElMessage.success('成功提交')
        drawer.value = false
        window.location.reload()
      } else {
        ElMessage.warning('提交失败')
      }
    } catch (error) {
      console.log(error)
    }
  } catch (error) {
    console.log(error)
  }
}

//删除用户信息
const deleteItem = async (id: any) => {
  let res = await deleteuserinfo(`_id=${id}`)
  if (res.code == 200) {
    ElMessage(res.message)
  } else {
    ElMessage.warning(res.message)
  }
  await UserInfoList()
}

//分页器
const handleCurrentChange = async (page: number) => {
  pagination.currentPage = page
  await UserInfoList()
}
const handleSizeChange = async (limit: number) => {
  pagination.pageSize = limit
  await UserInfoList()
}
//复选框发生改变
const selectChange = (val: any) => {
  selectArr.value = val
}
//批量删除
const deleteSelectItem = async () => {
  let selectId = selectArr.value.map((i) => {
    return i._id
  })
  const queryParams = selectId.map((id) => `_id=${id}`).join('&')
  let res = await deleteuserinfo(queryParams)
  if (res.code == 200) {
    ElMessage.success(res.message)
  } else {
    ElMessage.warning(res.message)
  }
  await UserInfoList()
}
//重置
const reset = async () => {
  inputName.value = ''
  await UserInfoList()
}
</script>

<style scoped lang="scss">
.topCard {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding: 26px;
  }
  .form {
    display: flex;
    justify-content: space-between;
  }
}
.bottomCard {
  .bottom-table {
    margin: 10px 0;
    width: 100%;
    .tags {
      display: flex;
      align-items: center;
      justify-content: center;
      .el-tag {
        cursor: pointer;
        margin: 0 6px;
      }
    }
  }
}
.el-form-item {
  margin-bottom: 0;
}
// el 头像
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// 右侧抽屉
.drawer {
  .el-form-item {
    margin-bottom: 24px;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
